//
//  FMDBDishManager.m
//  takeout
//
//  Created by Mac on 12-4-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "FMDBDishManager.h"
#import "FMDatabase.h"
#import "FMDBManager.h"
#import "DishCategory.h"
#import "Dish.h"
@implementation FMDBDishManager

//插入本地菜系
-(void) insertDishCategories:(FMDatabase *)db dishCategories:(DishCategory *)dishCategory supplierid:(NSInteger)supplierid{
    [db executeUpdate:@"INSERT INTO dish_category(id, name, supplierid) values(?,?,?)",[NSNumber numberWithInt:[dishCategory dishCategoryId]],[dishCategory dishCategoryName],[NSNumber numberWithInt:supplierid]];
    NSLog(@"插入本地菜系");
}


//插入本地菜品
-(void) insertDishes:(FMDatabase *)db dishCategories:(Dish *)dish{
    [db executeUpdate:@"INSERT INTO dish(id, name, picture, price, desc, dish_cate_id) values(?,?,?,?,?,?)",[NSNumber numberWithInt:[dish dishId]],[dish dishName],[dish imgUrl],[NSNumber numberWithFloat:[dish price]],[dish desc],[NSNumber numberWithInt:[dish dishCategoryId]]];
    NSLog(@"插入本地菜品");
}

//查询本地菜系
-(void) selectDishCategory{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    FMResultSet *rs = [db executeQuery:@"SELECT * FROM dish_category"];
    while ([rs next]){
        NSLog(@"查询本地菜系id%@ name%@ %@",[rs stringForColumn:@"id"],[rs stringForColumn:@"name"],[rs stringForColumn:@"supplierid"]);
    }
    [rs close];
//    [fmdbManager closeDataBase];
}

//查询本地菜品
-(void) selectDish{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    FMResultSet *rs = [db executeQuery:@"SELECT * FROM dish"];
    while ([rs next]){
        NSLog(@"查询本地菜品id%@ name%@ %@ %@ %@ %@",[rs stringForColumn:@"id"],[rs stringForColumn:@"name"],[rs stringForColumn:@"picture"],[rs stringForColumn:@"price"],[rs stringForColumn:@"desc"],[rs stringForColumn:@"dish_cate_id"]);
    }
    [rs close];
//    [fmdbManager closeDataBase];
}

//删除菜品
-(void) deleteDish:(NSString *)dishId{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    [db executeUpdate:@"DELETE FROM dish where id=?",dishId];
//    [fmdbManager closeDataBase];
}

//删除菜系
-(void) deleteDishCategory:(NSString *)DishCategoryId{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    [db executeUpdate:@"DELETE FROM dish_category where id=?",DishCategoryId];
//    [fmdbManager closeDataBase];
}


//从本地取得菜品
-(NSArray *)getAllDishesBySupIdFromLoc:(NSString *)supplierId{
    NSMutableArray *dishCategorys=[NSMutableArray arrayWithCapacity:2];
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    FMResultSet *dishCategoryRs = [db executeQuery:@"select * from dish_category where supplierid=?",supplierId];
    while ([dishCategoryRs next]) {
        DishCategory *dishCategory=[[DishCategory alloc]init];
        dishCategory.dishCategoryId=[dishCategoryRs intForColumn:@"id"];
        dishCategory.dishCategoryName=[dishCategoryRs stringForColumn:@"name"];
        NSString *dishCategoryIdToString = [NSString stringWithFormat:@"%d",dishCategory.dishCategoryId];
        FMResultSet *dishRs=[db executeQuery:@"select * from dish where dish_cate_id=?",dishCategoryIdToString];
        NSMutableArray *dishes=[NSMutableArray arrayWithCapacity:2];
        while([dishRs next]){
            Dish *dish=[[Dish alloc]init];
            dish.dishId=[dishRs intForColumn:@"id"];
            dish.dishName=[dishRs stringForColumn:@"name"];
            dish.imgUrl=[dishRs stringForColumn:@"picture"];
            dish.price=[dishRs doubleForColumn:@"price"];
            dish.desc=[dishRs stringForColumn:@"desc"];
            dish.dishCategoryId=[dishRs intForColumn:@"dish_cate_id"];
            [dishes addObject:dish];
        }
        dishCategory.dishes=dishes;
        [dishCategorys addObject:dishCategory];
    }
    return dishCategorys;
}




-(void)insertAllDishesBySupIdToLoc:(NSArray *)dishCategories supplierid:(NSInteger)supplierid{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    //    [db executeUpdate:@"DELETE FROM dish"];
    //    [db executeUpdate:@"delete from dish_category"];
    NSString *supplieridToString = [NSString stringWithFormat:@"%d",supplierid];
    NSArray * localDishes=[self getAllDishesBySupIdFromLoc:supplieridToString];
    
    if([localDishes count]==0){
        for(int i=0;i<[dishCategories count];i++){
            DishCategory *dishCategory=(DishCategory *)[dishCategories objectAtIndex:i];
            [self insertDishCategories:db dishCategories:dishCategory supplierid:supplierid];
            for(int i=0;i<[dishCategory.dishes count];i++){
                Dish *dish=(Dish *)[dishCategory.dishes objectAtIndex:i];
                [self insertDishes:db dishCategories:dish];
            }
        }
    } 
    else{
        for(int i=0;i<[dishCategories count];i++){
            DishCategory *dishCategory=(DishCategory *)[dishCategories objectAtIndex:i];
            NSString *dishCategoryIdToString = [NSString stringWithFormat:@"%d",[dishCategory dishCategoryId]];
            [self deleteDishCategory:dishCategoryIdToString];
            [self insertDishCategories:db dishCategories:dishCategory supplierid:supplierid];
            for(int i=0;i<[dishCategory.dishes count];i++){
                Dish *dish=(Dish *)[dishCategory.dishes objectAtIndex:i];
                NSString *dishIdToString = [NSString stringWithFormat:@"%d",[dish dishId]];
                [self deleteDish:dishIdToString];
                [self insertDishes:db dishCategories:dish];
            }
        }
        
    }
//    [fmdbManager closeDataBase];
}

//将用户在菜单页面选择的点菜信息保存到本地数据库
-(Boolean)insertDishesToShoppingCart:(NSArray *)dishesArray{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    for(int i =0;i<[dishesArray count];i++){
        NSDictionary *dishDic = [dishesArray objectAtIndex:i];
        NSInteger dishId = [[dishDic objectForKey:@"dishId"] intValue];
        NSString *dishName = [dishDic objectForKey:@"dishName"];
        NSInteger dishNumber = [[dishDic objectForKey:@"dishNumber"] intValue];
        float dishPrice = [[dishDic objectForKey:@"dishPrice"] floatValue];
        NSInteger shopId = [[dishDic objectForKey:@"shopId"] intValue];
        //判断如果已经保存过该菜，则执行更新
        FMResultSet *rs = [db executeQuery:@"SELECT * FROM shopping_cart_dish WHERE DISHID=?",[NSNumber numberWithInt:dishId]];
        if([rs next]) {
            NSInteger hisNumber = [rs intForColumn:@"dishNumber"];
            [db executeUpdate:@"UPDATE shopping_cart_dish SET dishName=?,dishNumber=?,dishPrice=?,shopId=? WHERE dishId=?",dishName,[NSNumber numberWithInt:(hisNumber+dishNumber)],[NSNumber numberWithFloat:dishPrice],[NSNumber numberWithInt:shopId],[NSNumber numberWithInt:dishId]];
        }
        //如果未保存过该菜，则新增
        else{
            [db executeUpdate:@"INSERT INTO shopping_cart_dish(dishId,dishName,dishNumber,dishPrice,shopId) VALUES(?, ?, ?, ?, ?)",[NSNumber numberWithInt:dishId],dishName,[NSNumber numberWithInt:dishNumber],[NSNumber numberWithFloat:dishPrice],[NSNumber numberWithInt:shopId]];
        }
        [rs close];
    }
    return TRUE;
}

//将用户点过菜的商家信息保存到本地数据库
-(Boolean)insertShopsToShoppingCart:(NSDictionary *)shopInfoDictionary{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    NSInteger shopId = [[shopInfoDictionary objectForKey:@"shopId"] intValue];
    NSString *shopName = [shopInfoDictionary objectForKey:@"shopName"];
    NSArray *phoneNumberAry = [shopInfoDictionary objectForKey:@"phoneNumber"];
    //将phoneAry里保存的电话号码按,号分割成一个字符串
    NSString *phoneNumber = [phoneNumberAry componentsJoinedByString:@","];
    [db executeUpdate:@"DELETE FROM shopping_cart_shop WHERE shopId=?",[NSNumber numberWithInt:shopId]];
    [db executeUpdate:@"INSERT INTO shopping_cart_shop(shopId,shopName,phoneNumber) VALUES(?, ?, ?)",[NSNumber numberWithInt:shopId],shopName,phoneNumber];
    return TRUE;
}

//查询用户已点过菜的商家信息
-(NSArray *)getShopInfo{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    FMResultSet *rs = [db executeQuery:@"SELECT * FROM shopping_cart_shop"];
    NSMutableArray *shopInfoArray=[[NSMutableArray alloc] init];
    while ([rs next]) {
        NSDictionary *shopInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:[[NSString alloc] initWithFormat:@"%d",[rs intForColumn:@"shopId"]],@"shopId",[rs stringForColumn:@"shopName"],@"shopName",[rs stringForColumn:@"phoneNumber"],@"phoneNumber", nil];
        [shopInfoArray addObject:shopInfoDic];
    }
    [rs close];
    return shopInfoArray;
}

//根据商家ID查询用户在这家店点的菜的信息
-(NSMutableArray *)getDishInfoByShopId:(NSInteger)shopId{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    FMResultSet *rs = [db executeQuery:@"SELECT * FROM shopping_cart_dish WHERE shopId=?",[NSNumber numberWithInt:shopId]];
    NSMutableArray *dishInfoArray=[[NSMutableArray alloc] init];
    while ([rs next]) {
        NSDictionary *dishInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:[[NSString alloc] initWithFormat:@"%d",[rs intForColumn:@"dishId"]],@"dishId",[rs stringForColumn:@"dishName"],@"dishName",[[NSString alloc] initWithFormat:@"%d",[rs intForColumn:@"dishNumber"]],@"dishNumber", [rs stringForColumn:@"dishPrice"],@"dishPrice",nil];
        [dishInfoArray addObject:dishInfoDic];
    }
    [rs close];
    return dishInfoArray;
}

//修改某一样菜的数量
-(void)updateDishNumber:(NSInteger)dishId newDishNum:(NSInteger)dishNum{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    [db executeUpdate:@"UPDATE shopping_cart_dish SET dishNumber=? WHERE dishId=?",[NSNumber numberWithInt:dishNum],[NSNumber numberWithInt:dishId]];
}

//在购物车页面删除某一样菜
-(void)deleteDishByDishIdInShoppingCart:(NSInteger)dishId{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    //获取此菜所属的商家ID
    FMResultSet *rs = [db executeQuery:@"SELECT shopId FROM shopping_cart_dish WHERE dishId=?",[NSNumber numberWithInt:dishId]];
    NSInteger shopId = 0;
    while ([rs next]) {
        shopId = [rs intForColumn:@"shopId"];
    }
    //删除此菜
    [db executeUpdate:@"DELETE FROM shopping_cart_dish WHERE dishId=?",[NSNumber numberWithInt:dishId]];
    //判断此菜所属的商家是否还有用户点的菜，如果没有，则将此商家从商家表中删除
    FMResultSet *rs2 = [db executeQuery:@"SELECT * FROM shopping_cart_dish WHERE shopId=?",[NSNumber numberWithInt:shopId]];
    if(![rs2 next]) {
        [db executeUpdate:@"DELETE FROM shopping_cart_shop WHERE shopId=?",[NSNumber numberWithInt:shopId]];
    }
}

//清空购物车
-(void)clearShoppingCart{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    [db executeUpdate:@"DELETE FROM shopping_cart_shop"];
    [db executeUpdate:@"DELETE FROM shopping_cart_dish"];
}

//根据商家ID获取商家信息
-(NSDictionary *)getShopInfoByDishId:(NSInteger)shopId{
    FMDBManager *fmdbManager= [[FMDBManager alloc]init];
    FMDatabase *db=[fmdbManager getDataBase];
    FMResultSet *rs = [db executeQuery:@"SELECT * FROM shopping_cart_shop WHERE shopId=?",[NSNumber numberWithInt:shopId]];
    NSDictionary *shopInfoDic;
    while ([rs next]) {
        shopInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:[[NSString alloc] initWithFormat:@"%d",[rs intForColumn:@"shopId"]],@"shopId",[rs stringForColumn:@"shopName"],@"shopName",[rs stringForColumn:@"phoneNumber"],@"phoneNumber",nil];
    }
    return shopInfoDic;
}

@end
